<template>
  <section class="todoapp">
    <todu-header @add="handleAdd"></todu-header>
    <todu-main :list="list2" @del="handleDel" @state="handleState" @changeAll="handleAll"></todu-main>
    <todu-footer
      :list="list"
      :flag="flag"
      @clearCompleted="handleClear"
      @changeFlag="
        (val) => {
          flag = val;
        }
      "
    ></todu-footer>
  </section>
</template>

<script>
import ToduFooter from "./components/ToduFooter.vue";
import ToduHeader from "./components/ToduHeader.vue";
import ToduMain from "./components/ToduMain.vue";
export default {
  components: { ToduHeader, ToduMain, ToduFooter },
  data() {
    return {
      // list: [
      //   { id: 12, name: "吃饭", isDone: false },
      //   { id: 14, name: "听歌", isDone: true },
      //   { id: 23, name: "洗澡", isDone: true },
      //   { id: 34, name: "睡觉", isDone: false },
      //   { id: 35, name: "游戏", isDone: false },
      // ],
      list:JSON.parse(localStorage.getItem('todo-list' || [])),
      flag: 1,
    };
  },
  methods: {
    handleDel(id) {
      this.list = this.list.filter((item) => item.id !== id);
    },
    handleAdd(todo) {
      this.list.unshift({
        id: +new Date(),
        name: todo,
        isDone: false,
      });
    },
    handleState(id) {
      const row = this.list.find((item) => item.id === id);
      row.isDone = !row.isDone;
    },
    handleClear() {
      this.list = this.list.filter((item) => item.isDone === false);
    },
    handleAll(val){
      this.list.forEach(item=>item.isDone = val)
    }
  },
  computed:{
      list2(){
        if(this.flag === 2){
          return this.list.filter(item=>item.isDone === false)
          }
          else if(this.flag === 3){
            return this.list.filter(item=>item.isDone === true)
          }
          else{
            return this.list
          }
      }
    },
  watch:{
    list:{
      handler(val){
        localStorage.setItem('todo-list',JSON.stringify(val))
      },
      deep:true,
    }
  }
};
</script>

<style></style>
